package com.hkbigdata.sink;

import com.alibaba.fastjson.JSON;
import com.hkbigdata.bean.WaterSensor;
import org.apache.flink.api.common.serialization.SimpleStringSchema;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.sink.RichSinkFunction;
import org.apache.flink.streaming.connectors.kafka.FlinkKafkaProducer;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.util.ArrayList;

/**
 * @author liuanbo
 * @creat 2024-04-18-9:16
 * @see 2194550857@qq.com
 */
public class Flink02_Sink_Mysql {
    public static void main(String[] args) throws Exception {
        ArrayList<WaterSensor> waterSensors = new ArrayList<>();
        waterSensors.add(new WaterSensor("sensor_1", 1607527992000L, 20));
        waterSensors.add(new WaterSensor("sensor_1", 1607527994000L, 50));
        waterSensors.add(new WaterSensor("sensor_1", 1607527996000L, 50));
        waterSensors.add(new WaterSensor("sensor_2", 1607527993000L, 10));
        waterSensors.add(new WaterSensor("sensor_2", 1607527995000L, 30));

        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment().setParallelism(1);

        env.fromCollection(waterSensors)
                .addSink(new RichSinkFunction<WaterSensor>() {
                    private Connection connection;
                    private PreparedStatement preparedStatement;

                    @Override
                    public void open(Configuration parameters) throws Exception {
                        connection = DriverManager.getConnection("jdbc:mysql://hadoop102:3306/test?useSSL=false", "root", "123456");
                        preparedStatement = connection.prepareStatement("insert into  sensor values (?,?,?)");
                    }

                    @Override
                    public void close() throws Exception {
                        connection.close();
                        preparedStatement.close();
                    }

                    @Override
                    public void invoke(WaterSensor value, Context context) throws Exception {
                        preparedStatement.setString(1, value.getId());
                        preparedStatement.setLong(2, value.getTs());
                        preparedStatement.setDouble(3, value.getVc());
                        preparedStatement.execute();
                    }
                });
        env.execute();
    }
}
